import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes } from '@/types/data'
import { CheckoutInfo, UserAddress } from '@/types/checkout'

export default defineStore('checkout', {
  state: () => ({
    checkoutInfo: {} as CheckoutInfo,
  }),
  actions: {
    async getCheckoutInfo() {
      const res = await request.get<ApiRes<CheckoutInfo>>('/member/order/pre')
      console.log(res)
      this.checkoutInfo = res.data.result
    },
    // 添加地址
    async addAddress(address: UserAddress) {
      await request.post('/member/address', address)
      // 添加完地址，重新渲染
      this.getCheckoutInfo()
    },
    async updateAddress(address: UserAddress) {
      await request.put(`/member/address/${address.id}`, address)
      // 添加完地址，重新渲染
      this.getCheckoutInfo()
    },
  },
  getters: {
    userAddress(): UserAddress | null {
      if (this.checkoutInfo.userAddresses.length === 0) {
        return null
      }
      const defaultAdd = this.checkoutInfo.userAddresses.find(
        (item) => item.isDefault === 0
      )
      if (defaultAdd) {
        return defaultAdd
      } else {
        return this.checkoutInfo.userAddresses[0]
      }
    },
  },
})
